/**
 * Created by Administrator on 2015/11/30 0030.
 */


var DB = require('../server/CRUD');
DB = new DB("menu");
var rest = require('rest');
var mime = require('rest/interceptor/mime');
var client = rest.wrap(mime, {mime: 'application/json'});
var config = require('./Config.js');

var logger = require('../utils/logger').logger


exports.register = function (app) {

    app.get("/menu", function (req, res, next) {
        username = req.signedCookies.username;
        if (username) {
            var build = function (data) {
                var list = {}
                list.group = app.getVip()
                list.data = data
                res.render("menu", {
                    title: "菜单管理",
                    list: list
                })
            }
            DB.read({}, function (list) {
                if (!list || !list.items) {
                    var data = config
                } else {
                    data = list.items[0]
                }
                build(data)
            });
        } else {
            res.redirect("/sign-in");
        }
    })

    app.post("/menu", function (req, res, next) {
        username = req.signedCookies.username;
        if (username) {

            var menu = req.body.menu;
            console.log("create menu");
            console.log(menu);
            if (menu) {
                app.locals.getToken().then(function (token) {
                    console.log("token:"+token.value);
                    var url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token.value;
                    var q = client({method: "POST", path: url, entity: menu}).then(function (data) {
                        return data.entity;
                    })
                    return q;
                }).then(function(result){
                    DB.deleteData({}, function () { // 删除旧数据
                        DB.create(app.locals.menu, function (r) {
                            app.locals.menu = menu;
                            res.json(result);
                        })
                    })
                }).catch(function(err){
                    res.json(err);
                })
            }
        } else {
            res.redirect("/sign-in");
        }
    })
}